<?php

defined('MYLITS') ? '' : exit('No direct script access allowed');

/**
 * @version     1.0.0
 * @package     mylits engine
 * @license     GNU General Public License version 3
 * @author      Arfan Fudyartanto D N <arfan@mylits.com> - http://engine.mylits.com
 */
class Mylits_Model {

    public $connection = array();
    public $config = array();
    public $component;
    public $process;
    private $sql;
    private $debugging = false;
    private $connectionNumber;

    public function __construct() {
        $this->config = Mylits_Config::getValue('db');

        foreach ($this->config as $connection_number => $conf) {
            $this->connection[$connection_number] = mysqli_connect('p:' . $conf['host'], $conf['user'], $conf['pass'], $conf['name']) or die("Error " . mysqli_error($this->connection[$connection_number]));
        }
    }

    /**
     * Method to set connection number of Mylits_Model object 
     * 
     * @param integer $number-> connection number
     */
    public function setConnectionNumber($number) {
        $this->connectionNumber = $number;
    }

    /**
     * Method to set sql file. sql file is query directory.
     * 
     * @param string $name -> name of sql file, {name}.mdls.sql.php
     */
    public function setSqlFile($name) {
        $this->sql = $name;
    }

    /**
     * Method to print out executed query from surrent Mylits_Model object
     */
    public function setDebugOn() {
        $this->debugging = true;
    }

    /**
     * Method to turn off debug mode
     */
    public function setDebugOff() {
        $this->debugging = false;
    }

    /**
     * Method to get query string from sql file
     * 
     * @param string $name -> query name, $query[{name_of_query}]
     * @param array $params
     * @return string Query
     */
    public function openQuery($name, $params = array()) {
        $Reflection = new ReflectionClass($this);
        $filePath = $Reflection->getFileName();
        $dir = str_replace(basename($filePath), '', $filePath);
        if (is_file($dir . '/' . $this->sql . '.mdls.sql.php')) {
            include $dir . '/' . $this->sql . '.mdls.sql.php';

            foreach ($params as $arg) {
                $query[$name] = preg_replace('/\?/', $arg, $query[$name], 1);
            }

            return str_replace('#_', $this->config[$this->connectionNumber]['prfx'], $query[$name]);
        }
    }

    /**
     * Method to run query
     * 
     * @param string $query
     * @return array -> result from executed query
     */
    public function runQuery($query) {
        if ($this->debugging) {
            echo "<pre>" . $query . "</pre>";
        }

        if (!empty($query)) {
            $result = mysqli_query($this->connection[$this->connectionNumber], $query);
            #remove white space in the beginning
            $query = preg_replace('/^((?=^)(\s*))|((\s*)(?>$))/si', '', $query);
            $is_select = preg_match("/^select/", strtolower($query));
            $return = array();
            if ($result) {
                if ($is_select) {
                    while ($obj = $result->fetch_object()) {
                        $return[] = (array) $obj;
                    }
                }
            } else {
                $content = "component : " . $this->component . "<br/>process : " . $this->process . "<br/>model : " . get_class($this) . "<br/>" . $query . "<br/><br/>" . mysqli_error($this->connection[$this->connectionNumber]);
                Mylits_Error::assign('mysql', $content);
            }

            if ($is_select) {
                return $return;
            } else {
                return $result;
            }
        } else {
            $content = "component : " . $this->component . "<br/>process : " . $this->process . "<br/>model : " . get_class($this) . "<br/><br/>Your query is empty";
            Mylits_Error::assign('mysql', $content);
        }
    }

    /**
     * Method to get last insert id of current mysqli connection
     * 
     * @return int 
     */
    public function lastInsertId() {
        $mysqli = $this->connection[$this->connectionNumber];
        return $mysqli->insert_id;
    }

    /**
     * method to open mysql transaction, set auto commit off
     */
    public function startTrans() {
        $mysqli = $this->connection[$this->connectionNumber];
        $mysqli->autocommit(FALSE);
    }

    /**
     * Method to end mysql transaction, commit transaction
     * 
     * @param boolean condition, will commit if true
     */
    public function endTrans($result) {
        if ($result) {
            $mysqli = $this->connection[$this->connectionNumber];
            $mysqli->commit();
        }
    }

}

?>
